这是编写接受带有可变数量参数的函数指针的函数模板的正确方法吗?

时间:2014-02-04 22:27:16

标签: c++ templates function-pointers variadic-templates

我有以下代码,

class ODBCFuncCall // Line 67
{
public:
    ODBCFuncCall(SQLHANDLE stmt, SQLHANDLE conn) : m_stmt(stmt), m_conn(conn) {}

    virtual ~ODBCFuncCall() {}

    template <typename... A>
    void RunStatementFunction(SQLRETURN (*in_func)(SQLHSTMT, A...), A... args)
    {
        in_func(m_stmt, args...);
    }

    virtual const char* GetFunctionName() = 0;

    virtual void Setup() = 0;
    virtual void Run() = 0;
    virtual void Cleanup() = 0;

protected:
    const SQLHANDLE m_stmt;
    const SQLHANDLE m_conn;
};

我正在尝试用VS2012 SP4编译。这完全是对它的抨击,这是我得到的错误样本:

Error   6   error C2059: syntax error : ')' \ODBCTask.h 75
Error   4   error C2065: 'A' : undeclared identifier    \ODBCTask.h 75
Error   2   error C2065: 'in_func' : undeclared identifier  \ODBCTask.h 75
Error   5   error C2143: syntax error : missing ')' before '...'    \ODBCTask.h 75
Error   1   error C2143: syntax error : missing ',' before '...'    \ODBCTask.h 74
Error   7   error C2238: unexpected token(s) preceding ';'  \ODBCTask.h 80
Error   3   error C2275: 'SQLHSTMT' : illegal use of this type as an expression \ODBCTask.h 75

当我注释掉'RunStatementFunction'时它编译得很好。 语法似乎对我来说是正确的,我可以通过谷歌搜索类似的东西找到...

2 个答案:

答案 0 :(得分:4)

是的,这是正确的:see it in action on ideone

使用2012年11月的CTP时,Variadic模板仅适用于VS 2012。这引入了一个单独的工具集,必须在项目属性中选择它。它应该用那个编译。

答案 1 :(得分:3)

我看到两个问题。第一版vs2012不支持可在生产代码中使用的实验性CTP之外的可变参数模板

其次,你应该完善你的函数指针的参数。

template <typename... As,typename...Ts>
void RunStatementFunction(SQLRETURN (*in_func)(SQLHSTMT, As...), Ts&&... args) 
{
  in_func(m_stmt, std::forward<Ts>(args)...);
}

应该消除优化构建中辅助函数的所有开销。

vs2013支持可变参数模板。