template <typename B, typename T = int> void Bar(B b = B(), T t = T()) {} Bar(10); // Bar<int, int> Bar(10L); // Bar<long, int> Bar(10L, 20L); // Bar<long, long> Bar(); // Compile error, couldn't deduce template parameter ‘B’
同樣的在Function Template overload的時候,也是地雷區。
1 2 3 4 5
template <typename T = int> void Foo(T t = T()) {} template <typename B, typename T = int> void Foo(B b = B(), T t = T()) {} Foo(12L); // Compile error, ‘Foo(long int)’ is ambiguous // void Foo(T) [with T = long int] and void Foo(B, T) [with B = long int; T = int] Foo(); // Compile OK, choose the first function
void sum(int n, long long int v, function<void (long long)> contWith) { if (n == 0) return contWith(v); return sum(n - 1, n + v, contWith); } sum(1000000000, 0, [] (long long v) { cout << v << endl; });
結果所有編譯器全掛了,同樣邏輯的程式碼用Haskell重寫一次
1 2 3
sum' n total cont | n == 0 = cont(total) | otherwise = sum' (n - 1) (total + n) cont
#include <stdio.h> using namespace std; const int n = 5; const int m = 5; constexpr int mul2(int x, int y) { return x * y; } int array[mul2(n, m)]; int main() { int x, y; scanf("%d %d", &x, &y); printf("arraySize = %lu\n", sizeof(array) / sizeof(array[0])); printf("mul2((x, y) = %d\n", mul2(x, y)); return 0; }
const int n = 5; const int m = 5; class Mul2 { int x, y; public: constexpr Mul2(int x_, int y_) : x(x_), y(y_) {} constexpr int operator()() { return x * y; } }; constexpr Mul2 mul2(n, m); int array[mul2()];