0

I'm attempting to specialize a function template but I'm getting the following error :

bar.cpp:12:39: error: template-id ‘getValue<>’ for ‘std::variant<int, double> Test::getValue(const string&)’ does not match any template declaration 12 | template <> std::variant<int, double> Test::getValue(const std:: string& name) { | ^~~~ bar.cpp:7:29: note: candidate is: ‘template<class T> T Test::getValue(const string&) const’ 7 | template <typename T> T getValue(const std::string& name) const; | ^~~~~~~~ 

Yet I can't find why this is the case, as far as I see I'm respecting the method signature.

#include <iostream> #include <unordered_map> #include <variant> class Test { Test(); template <typename T> T getValue(const std::string& name) const; std::unordered_map<std::string, std::variant<int, double>> dict_; }; template <> std::variant<int, double> Test::getValue(const std:: string& name) { // ... do things } 
2
  • 2
    You need to specify the template arguments in for the specialization: template <> std::variant<int, double> Test::getValue<std::variant<int, double>>(const std:: string& name) Commented Apr 18, 2022 at 12:18
  • Didn't work for a moment, had just forgotten the const on the left of the first curly brace, all good thank you ! Commented Apr 18, 2022 at 12:25

2 Answers 2

1

Template parameters need to be explicitely defined.

template <> std::variant<int, double> Test::getValue<std::variant<int, double>>(const std::string& name) const { std::cout << "Hello" << std::endl; } 
Sign up to request clarification or add additional context in comments.

Comments

1

Your specialized member function misses the const qualifier, which makes it inconsistent with the primary template inside the class. This should work

template <> std::variant<int, double> Test::getValue(const std:: string& name) const //^^^^ { } 

Demo

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.