Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
907 views
in Technique[技术] by (71.8m points)

c++ - Candidate template ignored because template argument could not be inferred

What is wrong with the following piece of code?

#include <iostream>

template<typename K>
struct A {
    struct X { K p; };
    struct Y { K q; };
};

template<typename K>
void foo(const typename A<K>::X& x, const typename A<K>::Y& y) {
    std::cout << "A" << std::endl;
}

int main() {
    A<float>::X x;
    A<float>::Y y;
    foo(x, y);  
}

clang gives the following error message:

17:2: error: no matching function for call to 'foo'
        foo(x, y);      
        ^~~
10:6: note: candidate template ignored: couldn't infer template argument 'K'
void foo(const typename A<K>::X& x, const typename A<K>::Y& y) {
     ^
1 error generated.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The argument K in const typename A<K>::X is not deducible. Basically, everything left of a :: is not deducible (if :: separates a nested-name).

It's trivial to see why it makes no sense to ask for deduction by running through this thought experiment:

struct A { typedef int type; }
struct B { typedef int type; }

template <typename T> void foo(typename T::type);

foo(5);   // is T == A or T == B ??

There's no one-to-one mapping from types to nested types: Given any type (such as int), there could be many ambient types of which it is a nested type, or there needn't be any.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...