Home > Enterprise >  C template function specialisation does not match specified type
C template function specialisation does not match specified type

Time:04-18

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
}

CodePudding user response:

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;
}

CodePudding user response:

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

  • Related