採取以下結構:簡化模板參數
template<typename T,T value>
struct A{
};
我想用這樣的:
A<12> a; //A<12> should become A<int,12>
但是,這是不允許的。爲什麼不允許? (有沒有解決方法?)
採取以下結構:簡化模板參數
template<typename T,T value>
struct A{
};
我想用這樣的:
A<12> a; //A<12> should become A<int,12>
但是,這是不允許的。爲什麼不允許? (有沒有解決方法?)
不知道你想要什麼,但也許這?
#include <iostream>
template <typename T, T value>
struct A {
void foo() const { std::cout << "A<int, " << value << ">::foo called\n"; }
};
// Sample partial specialization that you might want.
template <std::size_t value>
struct A<std::size_t, value> {
void foo() const { std::cout << "A<std::size_t, " << value << ">::foo called\n"; }
};
template <int N>
using B = A<int, N>;
template <int N, typename T = int>
using C = A<T, static_cast<T>(N)>;
int main() {
B<12> a;
a.foo(); // A<int, 12>::foo called
C<12> c;
c.foo(); // A<int, 12>::foo called
C<12, std::size_t> d;
d.foo(); // A<std::size_t, 12>::foo called
}
我想這比什麼都沒有好....但不是很酷 – DarthRubik
@DarthRubik我擴大了我的答案了一下。也許'C'比'B'更接近你想要的嗎?但'A <12>'是非法的語法,因爲它的聲明強制類型首先被列出。 – prestokeys
我知道....我只是希望有一個很酷的把戲 – DarthRubik
也許你會得到最接近的是使用元廠:
template<class T, T value>
struct A
{};
template<class T = int>
struct factory
{
template<T V> using A = ::A<T, V>;
};
int main()
{
auto x = factory<>::A<12> {};
auto y = factory<short>::A<45> {};
}
有人問起函數模板同樣的問題在這裏:http://stackoverflow.com/questions/ 37232082 /如何使模板參數我不能標記這個重複,直到我的答案被upvoted或接受。 –
想不到一種方式,除了一個類型別名。類似於'template using A_t = A ;'。請注意,這將引入另一種類型。如果它不是你想要的,那麼最初的課程可能設計得很糟糕。 –
DeiDei
如果有內存服務,投入C++ 17的其中一件事就是'template'不要緊,它在Oulu(6月底)投票。 –
chris