【问题标题】:Passing variadic function template arguments to another function将可变参数函数模板参数传递给另一个函数
【发布时间】:2014-06-29 01:38:20
【问题描述】:

我正在尝试将我的包传递给另一个函数,它看起来与我在教程中看到的相似,但显然不够相似:

class algorithm
    {
        typedef uint64_t time_type;
    protected:
        std::string name;
        time_type result;

        template <typename... Args>
        void execute(const Args&...);

    public:
        algorithm(std::string name);

        //virtual void prepareTest()=0;
        template <typename TimeT, typename... Args>
        void beginTest(const Args&...);
        void printResult();
        time_type getResult();

    };

    template <typename TimeT, typename... Args>
    void algorithm::beginTest(const Args&... args)
    {
        auto start = chrono::high_resolution_clock::now();

        execute(args...);

        auto duration = chrono::duration_cast<TimeT>
                    (chrono::high_resolution_clock::now() - start);

        result = duration.count();
    }

    template <typename... Args>
    void execute(const Args&... args)
    {
        //nothing here yet
    }

当我实例化一个算法和 beginTest() 时,我得到一个链接器错误:

const int n = 100000;
const int m = 1000;
algortest::algorithm brutus("brutus");
brutus.beginTest<chrono::milliseconds>(n, m);

架构 x86_64 的未定义符号:“void algortest::algorithm::execute(int const&, int const&)", 参考自: 无效算法::算法::beginTest >, int, int>(int const&, int const&) in main.o ld:未找到架构 x86_64 的符号

我做错了什么?另外,在派生类算法中覆盖 execute() 是否可行?

【问题讨论】:

  • 不是 100% 确定,如果这特别适用于您的用例(TL;DR;老实说),但这不是 std::forward() 模板函数的设计目的吗?
  • 显然你在成员函数execute的定义中缺少类作用域。

标签: c++ templates c++11 variadic-templates


【解决方案1】:

你忘了在execute 的定义前面加上algorithm:: 就是所有:-)

应该是:

template <typename... Args>
void algorithm::execute(const Args&... args)
{
    // ...
}

您可能还想对参数使用完美转发,而不是强制它们通过引用传递——而不是const Args&amp;...,在调用函数时使用Args&amp;&amp;...,然后使用std::forward&lt;Args&gt;(args)...

【讨论】:

    猜你喜欢
    • 2018-10-22
    • 2014-10-20
    • 2015-09-07
    • 1970-01-01
    • 2011-11-15
    • 2011-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多