Ker*_*taş 5 c++ templates template-argument-deduction c++17
我这里有一些代码
template<typename T, std::size_t size, typename funcType>
struct foo
{
public:
foo(const funcType& func) : m_func(func) {}
~foo() {}
void m_call() { m_func(); }
private:
const funcType& m_func;
T x[size];
};
void printString() { std::cout << "some string\n"; }
Run Code Online (Sandbox Code Playgroud)
我可以创建一个对象
foo<int, 3, void(*)()> someObject(printString);
Run Code Online (Sandbox Code Playgroud)
或者
foo<int, 3, decltype(printString)> someObject(printString);
Run Code Online (Sandbox Code Playgroud)
但是当我尝试这样做时:
foo<int, 3> someObject(printString);
Run Code Online (Sandbox Code Playgroud)
我在 g++ 10.2 上收到此错误
error: wrong number of template arguments (2, should be 3)
foo<int, 3> someObject(printString);
^
note: provided for 'template<class T, long unsigned int size, class funcType> struct foo'
struct foo
Run Code Online (Sandbox Code Playgroud)
为什么我不能这样做?编译器不知道printString是什么类型吗?
如果我将其更改foo为
template<typename funcType>
struct foo
{
public:
foo(const funcType& func) : m_func(func) {}
~foo() {}
void m_call() { m_func(); }
private:
const funcType& m_func;
};
Run Code Online (Sandbox Code Playgroud)
我可以正常创建
foo someObject(printString);
Run Code Online (Sandbox Code Playgroud)
我错过了什么吗?
根据cppreference:
仅当不存在模板参数列表时才执行类模板参数推导。如果指定了模板参数列表,则不会发生推导。
你上次的实验证实了这一点。为了推断,funcType您还需要在构造函数中提供其他模板化类型,以不提供任何模板参数列表。
您可以将其他模板与构造函数绑定,例如使用以下构造:
#include <iostream>
template<typename T, std::size_t size, typename funcType>
struct foo
{
public:
foo(T (&arr)[size], const funcType& func) : m_func(func) {}
~foo() {}
void m_call() { m_func(); }
private:
const funcType& m_func;
T x[size]{};
};
void printString() { std::cout << "some string\n"; }
void test() {
foo someObject("test", printString);
}
Run Code Online (Sandbox Code Playgroud)