3
我正在玩一個通用模板模板函數來將容器輸出到控制檯。模板模板函數中默認的const char *模板參數
爲此,我希望提供一個默認的分隔符。它的工作原理默認爲const char模板參數(但我需要做一個愚蠢的字符串構造)或默認const char *函數參數(我知道這是一個非常好的解決方案,可能是首選)。
我想知道的是,如果有一種方法將模板參數默認爲特定的const char *值?因爲模板參數是爲了聲明類型而不是像(*,&等等 - 但const是否工作?)的衍生物我不確定這是可能的,但是默認的模板參數並且比下面的第一個實現更有效率是我期待的對於。
#include <cstdlib>
#include <iostream>
#include <thread>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <iterator>
using namespace std;
// This Works
template <template <typename , typename > class Container, class Element, class Allocator, const char sep= ','>
void displayContents(const Container<Element, Allocator>& inputContainer)
{
string seperator(1, sep);
copy(inputContainer.cbegin(), inputContainer.cend(), ostream_iterator<Element>(cout, seperator.c_str())); // not all that efficient...
cout << endl;
};
// This works fine
template <template <typename, typename > class Container, class Element, class Allocator>
void displayContentsWithDefaultArgs(const Container<Element, Allocator>& inputContainer, const char* sep = ",")
{
copy(inputContainer.cbegin(), inputContainer.cend(), ostream_iterator<Element>(cout, sep));
cout << endl;
};
// how can we get this to work (more effectively than displayContents above?)
template <template <typename, typename > class Container, class Element, class Allocator, const char* sep = ",">
void displayContentsWithDefaultTemplateArgs(const Container<Element, Allocator>& inputContainer)
{
copy(inputContainer.cbegin(), inputContainer.cend(), ostream_iterator<Element>(cout, sep));
cout << endl;
};
int main(int argc, char** argv) {
vector<int> v = { 1 ,2 ,3, 4 };
vector<int> v1;
copy(v.cbegin(), v.cend(), back_inserter(v1));
displayContents(v1);
displayContentsWithDefaultArgs(v1);
displayContentsWithDefaultTemplateArgs(v1);
return 0;
}
怎麼樣:'模板<模板<類型名稱,類型名>類容器,類Element,類分配器,類月=爲const char *> 無效displayContentsWithDefaultTemplateArgs( const Container&inputContainer,Sep sep =「,」)'? –
從技術上講,它的工作原理和我所要求的一致。如果你想寫出來,只要沒有人能夠想出24小時內只使用模板參數默認值的解決方案,我會接受它。 –
注意:這應該是'template void display ...(const Container&)'並且在裏面使用'typename Container :: value_type'。 –