首页 > 解决方案 > 为什么我不能推断出类模板参数之一?

问题描述

我这里有一些代码

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

我可以创建一个对象

foo<int, 3, void(*)()> someObject(printString);

或者

foo<int, 3, decltype(printString)> someObject(printString);

但是当我尝试这样做时:

foo<int, 3> someObject(printString);

我在 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
       

为什么我不能这样做?编译器不知道是什么类型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;
};

我可以正常创建

foo someObject(printString);

我错过了什么吗?

标签: c++templatesc++17template-argument-deduction

解决方案


使用模板函数创建对象并从函数调用中扣除缺少的模板参数。像这样的东西。

template<typename T, std::size_t Size, typename FunctionT>
foo<T, Size, FunctionT> create_foo(const FunctionT &func) {
    return foo<T, Size, FunctionT>(func);
} 

auto foo_obj = create_foo<int, 3>(printString);

推荐阅读