C ++模板重载调用

时间:2017-03-23 12:10:15

标签: c++ function templates call overloading

我正在尝试实现一个执行模式,该模式接受任何函数并使用自己的条件/准备执行它。无论这是一件有用的事情,它都无法奏效。我似乎无法访问"执行" -function的模板重载(在" main"中调用)。

具体来说:为什么我不能调用Execute的重载模板函数?

这是完整的程序:

#include "stdafx.h"
#include <functional>

class TransparentFunctionWrapper
{
public:
    virtual void Execute(std::function<void()> executeFunction) = 0;

    template<class C>
    C Execute(std::function<C(void)> executeFunction) // template-overload of the abstract function which will implicitly call it
    {
        C ret;
        Execute( // calls the abstract function with a lambda function as parameter
        [ret, executeFunction](void) -> C       // lambda declaraction
        {                                       //
            ret = executeFunction;              // lambda body
        });                                     // 
        return ret;
    }
};

class ExampleExecutor : public TransparentFunctionWrapper
{
public:
    virtual void Execute(std::function<void()> executeFunction)
    {
        printf("executed before.");
        executeFunction();
        printf("executed after.");
    }
};

void DoStuff() {}
int ReturnStuff() { return -5; }

int main()
{
    ExampleExecutor executor;

    executor.Execute(DoStuff);
    int i = executor.Execute<int>(ReturnStuff);     // Why does this not work? ERROR: "type name is not allowed"

    getchar();
    return 0;
}

注意:Visual Studio标记

Execute<int>(ReturnStuff) // "int" is marked as Error: type name is not allowed

编译发出错误

"type 'int' unexpected"

感谢所有愿意提供帮助的人!

1 个答案:

答案 0 :(得分:1)

ExampleExecutor::Execute未覆盖TransparentFunctionWrapper::Execute,而是将其隐藏在executor.Execute<int>来电中。

您必须明确呼叫TransparentFunctionWrapper::Execute,因为ExampleExecutor::Execute隐藏了int i = executor.TransparentFunctionWrapper::Execute<int>(ReturnStuff); 。这是一种可能的方法:

<form name="mainform" id="mainform">
    <md-input-container class="md-block">
      <label>first</label>
      <input name="capital" ng-model="capital" validatecapitalparts>
    </md-input-container>

    <div layout-gt-sm="row">
    <md-input-container class="md-block" flex-gt-sm>
      <label>second</label>
      <input name="onecost" ng-model="onecost">
    </md-input-container>

</form> 

<h1>{{mainform.capital.$valid}}</h1>
<h1>{{mainform.onecost.$valid}}</h1>

live example on coliru