2017-07-08 89 views
4

我不是新來的模板,但我遇到了一個相當好奇的問題,我需要將模板類型分離爲我正在處理的數據序列化程序的組件。這很難解釋,所以我已經證明了它。模板實例化失敗:編譯器選擇不正確的重載函數

這是我簡化的示例問題example.cpp。

template<typename T> void foo(T& arg) { } 
template<typename T, typename V> void foo(T<V>& arg) { } 

int main(int argc, char *argv[]) 
{ 
    foo(argc); 
    return 0; 
} 

我得到一個錯誤,然後這似乎表明它試圖實例功能時,只有其中一人是合適的警告。

$ g++ -Wall -W example.cpp 
example.cpp:2:43: error: ‘T’ is not a template 
template<typename T, typename V> void foo(T<V>& arg) { } 
             ^
example.cpp: In instantiation of ‘void foo(T&) [with T = int]’: 
example.cpp:6:11: required from here 
example.cpp:1:34: warning: unused parameter ‘arg’ [-Wunused-parameter] 
template<typename T> void foo(T& arg) { } 
            ^~~ 

有關如何解決我的問題和/或防止這種困惑的任何建議?

+1

的情況下,沒有人提到它,感謝張貼產生的問題*最小*完整的例子的縮影。如果你能把它變得更小,我不會看到如何。完美詮釋。 – WhozCraig

回答

7

模板模板參數(參數本身是可引用的模板)需要與您使用的語法不同的語法。正如你寫的那樣,編譯器並不認爲T是一個模板,所以語法T<V>是沒有意義的。

template< template<class> class T, class V> void foo(T<V>& arg>) 

將是一個正確的例子。

#include <iostream> 

template<typename T> void foo(T& arg) 
{ 
    std::cout << __PRETTY_FUNCTION__ << '\n'; 
} 

template<template<class> class T, class V> void foo(T<V>& arg) 
{ 
    std::cout << __PRETTY_FUNCTION__ << '\n'; 
} 


template<class T> 
struct Bar 
{ 

}; 

int main(int argc, char *argv[]) 
{ 
    foo(argc); 

    Bar<int> bar; 
    foo(bar); 

    return 0; 
} 

輸出

void foo(T &) [T = int] 
void foo(T<V> &) [T = Bar, V = int] 
+0

快速問題:在哪裏定義了__PRETTY_FUNCTION__? –

+1

@FrancisCugler它是一個gcc/clang的東西。編譯器提供的宏。 – WhozCraig

+0

啊好吧我在窗戶上;使用MSVC所以我猜我必須堅持使用'__FUNCTION__',但它只給出'foo'中的名字,除非有一個相當於我不知道的名字。 –

相關問題