Tag Archives: c++

A Quiz of C++ const

在vs2010环境下, 如下程序会输出什么?

#include <string>
#include <iostream>
using namespace std;

template<class T>
struct print;

template<>
struct print<int> { static string name() { return "int"; } };

template<class T>
struct print<T&> { static string name() { return print<T>::name() + " &"; } };

template<class T>
struct print<const T> { static string name() { return "const " + print<T>::name(); } };

// just utility functions above

struct S { int i; };

template<class T>
void foo(T) { cout << print<T>::name() << endl; }

template<class T>
void bar(T&) { cout << print<T>::name() << endl; }

int main() {
    int i;
    const int ci = 0;
    const int *pci = &i;
    S s;
    const S *pcs = &s;

    foo(i);
    foo(ci);
    foo(*pci);
    foo(pcs->i);

    bar(i);
    bar(ci);
    bar(*pci);
    bar(pcs->i);

    {
        auto a1 = i;
        auto a2 = ci;
        auto a3 = *pci;
        auto a4 = pcs->i;
        cout << print<decltype(a1)>::name() << endl;
        cout << print<decltype(a2)>::name() << endl;
        cout << print<decltype(a3)>::name() << endl;
        cout << print<decltype(a4)>::name() << endl;
    }

    {
        auto& a1 = i;
        auto& a2 = ci;
        auto& a3 = *pci;
        auto& a4 = pcs->i;
        cout << print<decltype(a1)>::name() << endl;
        cout << print<decltype(a2)>::name() << endl;
        cout << print<decltype(a3)>::name() << endl;
        cout << print<decltype(a4)>::name() << endl;
    }

    cout << print<decltype(i)>::name() << endl;
    cout << print<decltype(ci)>::name() << endl;
    cout << print<decltype(*pci)>::name() << endl;
    cout << print<decltype(pcs->i)>::name() << endl;

    cout << print<decltype((i))>::name() << endl;
    cout << print<decltype((ci))>::name() << endl;
    cout << print<decltype((*pci))>::name() << endl;
    cout << print<decltype((pcs->i))>::name() << endl;

    return 0;
}

现在还敢说你精通C++吗?

答案参见此文, 以及我的笔记.

Typeclass & CRTP & boost::operators

今天把Haskell的Typeclass Eq和Ord在C++中用CRTP做了个简单的实现, 写完了才想起来boost里也有类似的(更强大)实现.

Continue Reading »

PIMPL & Const & Pointer

PIMPL是C++中一个古董级的隐藏实现的技巧, 通常当我们需要设计一个类而又只希望暴露它的接口时有两种选择. 一是写一个抽象类, 然后继承它; 二是使用PIMPL, 把实现塞到cpp文件里隐藏起来. 其原理在pongba的blog上有很好的阐述. 本文主要讲一下PIMPL实现过程中容易被忽略的const指针问题.

Continue Reading »