簡體   English   中英

在類模板中調用模板化仿函數

[英]Calling a templated functor in a class template

有沒有辦法調用類模板Foo的仿函數operator()( int ) ,如下所示( 在線版本

template<typename T>
struct Foo
{
    template<typename U>
    void operator()( int )
    {
    }
};

int main(int argc, char *argv[])
{
    Foo<char> foo;
    foo<bool>( 42 );
}

我在gcc 4.9.3中收到錯誤消息

error: expected primary-expression before ‘bool’
  foo<bool>( 42 );

如果成員函數不是函子並且前綴為:: ,那么我會在template前面加上template . ,或-> 沒有一些幫助,編譯器就不知道如何解析這個表達式; 作為函數或foo<int>類型的匿名對象的實例化。

是的,但它很難看:

foo.operator()<bool>( 42 );

它會起作用;

foo.operator()<bool>( 42 );

運算符最適合使用推導出的模板參數類型。

您沒有提供使用它的上下文的足夠細節,作為您可以考慮的替代方案;

  • 使調用操作符成為成員函數,從而允許顯式模板類型參數
  • 標簽調度機制
  • 接受類型U作為參數

例如;

template<typename U>
void operator()( int, U&& /*initial*/ )
{
  // use the initial value of U
}
// called as...

foo(42, true); // U is bool in your example

或者只是成員函數;

template<typename U>
void my_func( int )
{
}
// called as...

foo.my_fun<bool>( 42 );

不幸的是你需要使用foo.operator()<bool>(42); 為了這。 foo<bool>對C ++ 14變量模板,而不是模板調用運算符有效。

您可以做的是標記類型並將其作為參數傳遞給調用運算符以推斷出正確的類型:

//tag
template <typename T>
struct type{};

template<typename T>
struct Foo
{
    template<typename U>
    //deduction on the tagged type
    void operator()( type<U>, int )
    {
    }
};

int main(int argc, char *argv[])
{
    Foo<char> foo;
    foo( type<bool>{}, 42 );
    //   ^^^^^^^^^^^^ pass tag
}

你可以使用標簽的C ++ 14變量模板使這個更好一些:

template <typename T>
struct type_t{};

//variable template for nicer usage
template <typename T>
type_t<T> type;

template<typename T>
struct Foo
{
    template<typename U>
    void operator()( type_t<U>, int )
    {
    }
};

int main(int argc, char *argv[])
{
    Foo<char> foo;
    foo( type<bool>, 42 );
    //don't need {}^
}

暫無
暫無

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

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