Note that there are some explanatory texts on larger screens.

plurals
  1. POType checking template class parameters
    text
    copied!<p>I am trying to achieve type checking of template class parameters by disallowing implicit type conversions such as string->bool thereby throwing compile error. The specific scenario is a simple one as follows:</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; using namespace std; template &lt;class T&gt; class myPair { T a, b; public: myPair(T first, T second ) { a = first; b = second; } void test(); }; typedef myPair&lt;bool&gt; boolParm; template&lt;class T&gt; void myPair&lt;T&gt;::test() { if(a == true) { cout &lt;&lt; "a is true" &lt;&lt; endl; } else { cout &lt;&lt; "a is false" &lt;&lt; endl; } if(b == true) { cout &lt;&lt; "b is true" &lt;&lt; endl; } else { cout &lt;&lt; "b is false" &lt;&lt; endl; } } int main() { boolParm myObj(false, "false"); myObj.test(); return 0; } </code></pre> <p>The output of the above scenario is undesirable since the user may inadvertently pass 2 different types: bool and string and receive the first one as false (correct since passed as bool) but the second one will be true (incorrect since implicit type conversion from string to bool). I wish to restrict the user code in main() to throw compile errors and disallowing string/int parameters to pass in the constructor. It should only allow bool. I tried by using an overloaded constructor myPair(bool first, string second) but it didn't match since I guess the implicit type conversion from string->bool happens before the constructor is called. Is there any solution using template specializations in this scenario? Any help is highly appreciated Thanks</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload