2013-04-25 132 views
4

我已經創建了一個矩陣類,並且想要添加兩個不同數據類型的矩陣。像int和double return類型的矩陣應該是雙倍的。我怎樣才能做到這一點??? 這是我的代碼返回類型模板類未知

template<class X> 
class Matrix 
{ 
.......... 
........ 
template<class U> 
Matrix<something> operator+(Matrix<U> &B) 
{ 
if((typeid(a).before(typeid(B.a)))) 
Matrix<typeof(B.a)> res(1,1); 
else 
Matrix<typeof(a)> res(1,1); 
} 

應該是什麼「東西」在這裏???

也應該怎麼做,以便我可以使用「res」之外如果else語句?

+2

像['std :: common_type'](http://en.cppreference.com/w/cpp/types/common_type)? – dyp 2013-04-25 23:05:57

回答

5

可以同時處理與 C++ 11的自動返回式語法的@DyP慷慨援助:)這些問題。

template<typename U> 
Matrix <decltype(declval<X>()+declval<U>())> operator+(const Matrix<U> &B) const 
{ 
    Matrix< decltype(declval<X>() + declval<U>()) > res; 

    // The rest... 
} 

有了這個語法,你的「東西」就是C++通常在添加兩種模板類型時產生的類型。

+0

@DyP這是C++ 11的試用版。你會推薦'declval ()'我發佈的內容嗎? – 2013-04-25 23:18:03

+1

我想過使用'template Matrix ()+ declval ())> operator +(Matrix const & p);' – dyp 2013-04-25 23:19:58

+0

我不能得到它....我得到以下錯誤... ..../usr/include/C++/4.6/bits/C++ 0x_warning.h:32:2:error:#error該文件需要對即將到來的ISO C++標準C++ 0x的編譯器和庫支持。支持目前是實驗性的,並且必須使用-std = C++ 0x或-std = gnu ++ 0x編譯器選項啓用。 inserter.cpp:201:20:錯誤:'declval'未在此範圍內聲明 inserter.cpp:201:33:error:'declval'未在此範圍內聲明 inserter.cpp:201:45:錯誤:函數調用不能出現在常量表達式中 inserter.cpp:201:46:error :template argument 1 is invalid – 2013-04-25 23:27:46

4

嘗試common_type

#include <type_traits> 

template <typename T> 
class Matrix 
{ 
    // ... 

    template <typename U>  
    Matrix<typename std::common_type<T, U>::type> 
    operator+(Matrix<U> const & rhs) 
    { 
     typedef typename std::common_type<T, U>::type R; 

     Matrix<R> m; // example 
     // ... 
     return m; 
    } 
}; 
+0

它不工作m得到以下錯誤/usr/include/c++/4.6/bits/c++0x_warning.h:32:2:錯誤:#error該文件需要編譯器和庫支持即將到來的ISO C++標準,C++ 0x中。此支持目前是實驗性的,必須使用-std = C++ 0x或-std = gnu ++ 0x編譯器選項啓用。 inserter.cpp:201:28錯誤:名稱空間'std'中的'common_type'未命名類型 inserter.cpp:201:39:error:預期模板參數在'<'令牌之前 inserter.cpp:201 :39:error:expected'>'before'<'token – 2013-04-25 23:21:21

+1

@TilakRajSingh這些特性是C++ 11的特性 - 可以用-std = C++ 0x進行編譯或者使用boost或者索要C++ 03解決方案:) – dyp 2013-04-25 23:24:05

+0

我在Ubuntu中使用g ++編譯器12.04 – 2013-04-25 23:33:17