首页 > 解决方案 > 使用类模板参数推导制作静态接口

问题描述

我想创建一些宏来为模板化参数传递、存储等创建静态接口。我正在使用类模板参数推导,但我碰壁了。

#include <iostream>

template <typename Type>
struct Person
{
    Type &object;

    Person(Type &object) : object(object) {}

    void walk(unsigned steps)
    {
        object.walk(steps);
    }

    void talk(const std::string &words)
    {
        object.talk(words);
    }
};

struct MySelf
{
    void walk(unsigned steps)
    {
        std::cout << "walking: " << steps << std::endl;
    }

    void talk(const std::string &words) const
    {
        std::cout << "talking: " << words << std::endl;
    }
};

template <typename Type>
void testNConst(Person<Type> object)
{
    object.walk(50);
    object.talk("testing");
}

template <typename Type>
void testConst(Person<const Type> object)
{
    object.talk("testing");
}

int main()
{
    MySelf myself;

    testNConst(Person{myself}); // compiles

    testNConst(myself);         // does not compile
    testConst(myself);          // does not compile

    return 0;
}

输出:

../../../../src/py.com.personal/other/hanaTest/main.cpp:53:5: error: no matching function for call to 'testNConst'
    testNConst(myself);         // does not compile
    ^~~~~~~~~~
../../../../src/py.com.personal/other/hanaTest/main.cpp:35:6: note: candidate template ignored: could not match 'Person<type-parameter-0-0>' against 'MySelf'
void testNConst(Person<Type> object)
     ^
../../../../src/py.com.personal/other/hanaTest/main.cpp:54:5: error: no matching function for call to 'testConst'
    testConst(myself);          // does not compile
    ^~~~~~~~~
../../../../src/py.com.personal/other/hanaTest/main.cpp:42:6: note: candidate template ignored: could not match 'Person<const type-parameter-0-0>' against 'MySelf'
void testConst(Person<const Type> object)
     ^
2 errors generated.

有任何想法吗?

标签: c++c++17

解决方案


类模板参数推导仅适用创建对象(变量声明等)。

它根本不适用于函数参数或函数返回类型。您不能调用testNConst(myself),因为myself它不适Person<T>用于某些T- 正常的函数扣除规则适用。


简而言之:

template <typename T> struct X { X(T ); }; 

X x = 42;                 // ok, ctad here

template <typename T>
void foo(X<T> );
foo(42);                  // error, ctad doesn't apply here

X bar() { return 42; }    // error, ctad doesn't apply here either

推荐阅读