簡體   English   中英

為什么我不能推導出 class 模板 arguments 之一?

[英]Why can't I deduce one of the class template arguments?

我這里有一些代碼

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

我可以創建一個 object

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

我錯過了什么嗎?

根據cppreference

Class 模板參數推導僅在不存在模板參數列表時執行。 如果指定了模板參數列表,則不會進行推導。

你上次的實驗證實了這一點。 要推斷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);

}

神螺栓

使用模板 function 創建 object 並從 ZC1C425268E68384D1AB5Z074C1 調用中扣除缺少的模板 arguments。 像這樣的東西。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM